import {
  CloseCircleOutlined,
  FileImageOutlined,
  HolderOutlined,
} from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import { Radio, Tooltip } from 'antd';
import { useState } from 'react';
import ClarificationModal from '@/components/Template/ClarificationModal';
import type { DragItemType, OptionType, TemplateType } from '@/types/template';

interface AddedItemPropsType {
  type: TemplateType;
  item: DragItemType;
  onClick?: (item: DragItemType) => void;
  onDelete?: (item: DragItemType) => void;
  onValueChange?: (item: DragItemType, value: string, reason?: string) => void;
}
const AddedItem = ({
  type,
  item,
  onClick,
  onDelete,
  onValueChange,
}: AddedItemPropsType) => {
  const [open, setOpen] = useState(false);
  const [value, setValue] = useState('');

  const classNameMap = {
    ENName: 'en-name-item',
    Address: 'address-item',
    Photo: 'photo-item',
  };
  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    onDelete?.(item);
  };
  const handleValueChange = (_item: DragItemType, value: string) => {
    if (type === 'clarification') {
      setValue(value);
      setOpen(true);
    }
    if (type === 'replyClarification') {
      onValueChange?.(item, value);
    }
  };
  const handleSubmit = (reason: string) => {
    onValueChange?.(item, value, reason);
    setOpen(false);
  };
  return (
    <>
      <div
        key={item.id.toString()}
        className={`add-item ${type} ${classNameMap[item.type as keyof typeof classNameMap] || ''}`}
        onClick={() => onClick?.(item)}
      >
        <Item type={type} item={item} onValueChange={handleValueChange} />
        {type === 'edit' && (
          <div className="operation">
            <CloseCircleOutlined onClick={handleDelete} />
          </div>
        )}
        {type === 'edit' && (
          <div className="drag-handle">
            <HolderOutlined />
          </div>
        )}
      </div>
      <ClarificationModal
        item={item}
        value={value}
        open={open}
        onCancel={() => setOpen(false)}
        onSubmit={handleSubmit}
      />
    </>
  );
};

type ItemPropsType = Pick<
  AddedItemPropsType,
  'type' | 'item' | 'onValueChange'
>;
const Item = ({ type, item, onValueChange }: ItemPropsType) => {
  if (item.type === 'ENName') {
    return <ENNameItem type={type} item={item} />;
  }
  if (item.type === 'Address') {
    return <AddressItem item={item} />;
  }
  if (item.type === 'Photo') {
    return <PhotoItem item={item} />;
  }
  if (item.type === 'Empty') {
    return <EmptyItem type={type} />;
  }
  return <CustomItem type={type} item={item} onValueChange={onValueChange} />;
};
const CustomItem = ({ type, item, onValueChange }: ItemPropsType) => {
  let options: OptionType[] | null = null;
  try {
    options = JSON.parse(item.options || '[]');
  } catch {
    options = null;
  }
  const handleValueBlur = (e: React.FocusEvent<HTMLDivElement>) => {
    const value = e.target.textContent;
    if (value !== item.value) {
      onValueChange?.(item, value || '');
    }
  };
  const handleRadioValueChange = (e: RadioChangeEvent) => {
    onValueChange?.(item, e.target.value || '');
  };
  const RadioValueProps = ['clarification', 'replyClarification'].includes(type)
    ? {
        defaultValue: item.value,
        onChange: handleRadioValueChange,
      }
    : {
        value: item.value,
      };
  return (
    <>
      {item.title || item.enTitle ? (
        <div className="item title">
          <div>{item.title}</div>
          <div>{item.enTitle}</div>
        </div>
      ) : null}
      {options?.length ? (
        <Tooltip title={item.reason || ''}>
          <div className={`editable-dom ${item.reason && 'danger'}`}>
            <Radio.Group {...RadioValueProps}>
              {options.map((option) => (
                <Radio key={option.value} value={option.value}>
                  <div className="radio-content">
                    <span>{option.label}</span>
                    <span>{option.enLabel}</span>
                  </div>
                </Radio>
              ))}
            </Radio.Group>
          </div>
        </Tooltip>
      ) : item.value || item.valueDesc ? (
        <div className="item value">
          {['clarification', 'replyClarification'].includes(type) ? (
            <Tooltip title={item.reason || ''}>
              <div
                className={`editable-dom ${item.reason && 'danger'}`}
                contentEditable="true"
                suppressContentEditableWarning
                onBlur={handleValueBlur}
              >
                {item.value}
              </div>
            </Tooltip>
          ) : (
            <div>{item.value}</div>
          )}
          {item.valueDesc && <div>{item.valueDesc}</div>}
        </div>
      ) : null}
    </>
  );
};
const ENNameItem = ({ type, item }: ItemPropsType) => {
  const name = item.value.split(' ');
  return (
    <>
      <div className="item title">
        <div>{item.title}</div>
        <div>{item.enTitle}</div>
      </div>
      <div className="item value">
        {['clarification', 'replyClarification'].includes(type) ? (
          <div
            className="editable-dom"
            contentEditable="true"
            suppressContentEditableWarning
          >
            {name[1]}
          </div>
        ) : (
          <div>{name[1]}</div>
        )}
        <div>姓氏 Surname</div>
      </div>
      <div className="item value">
        {['clarification', 'replyClarification'].includes(type) ? (
          <div
            className="editable-dom"
            contentEditable="true"
            suppressContentEditableWarning
          >
            {name[0]}
          </div>
        ) : (
          <div>{name[0]}</div>
        )}
        <div>名字 Other name</div>
      </div>
    </>
  );
};
const AddressItem = ({ item }: Pick<AddedItemPropsType, 'item'>) => {
  const address = item.value.split(',');
  return (
    <div className="address-content">
      <div className="item title">
        <div>{item.title}</div>
        <div>{item.enTitle}</div>
      </div>
      <div className="address">
        <div className="address-item">
          <div className="item value">
            <div>{address[0]}</div>
          </div>
        </div>
        <div className="address-item">
          <div className="item value">
            <div>{address[1]}</div>
          </div>
        </div>
        <div className="address-item">
          <div className="item title">
            <div>分区</div>
            <div>District</div>
          </div>
          <div className="item value">
            <div>{address[2]}</div>
          </div>
        </div>
        <div className="address-item">
          <div className="item title">
            <div>国家/地区</div>
            <div>Country/Region</div>
          </div>
          <div className="item value">
            <div>{address[3]}</div>
          </div>
        </div>
      </div>
    </div>
  );
};
const PhotoItem = ({ item }: Pick<AddedItemPropsType, 'item'>) => {
  return (
    <div className="photo">
      {item.value ? (
        <img src={item.value} alt="" />
      ) : (
        <FileImageOutlined className="icon-photo" />
      )}
    </div>
  );
};
const EmptyItem = ({ type }: Pick<AddedItemPropsType, 'type'>) => {
  return <div className="empty">{type === 'edit' ? '占位控件' : ''}</div>;
};

export default AddedItem;
